package cn.bisoft.java.util.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class DBUtil
{
	public static void main(String[] args) throws Exception
	{
		DBUtil.importData("codecounter", "C:/Documents and Settings/tl/桌面/src/代码统计.txt", "\t", false);
	}
	
	private static Connection conn;
	
	static 
	{
		String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String url = "jdbc:sqlserver://192.168.0.160:1433;databaseName=AgentPortalDev;selectMethod=cursor";
		String user = "sa";
		String pass = "123456";
		
		try
		{
			Class.forName(driver);
			
			conn = DriverManager.getConnection(url, user, pass);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void importData(String tableName, String srcPath, String split, boolean hasPk) throws Exception
	{
		BufferedReader br = new BufferedReader(new FileReader(srcPath));
		BufferedWriter bw = new BufferedWriter(new FileWriter(srcPath + ".sql"));
		
		String line = null;
		String[] fields = null;
		String sql = null;
		
		while ((line = br.readLine()) != null)
		{
			fields = line.split(split);
			
			sql = "";
			
			sql += "insert into " + tableName + " values ( ";
			
			if (hasPk)
			{
				sql += "null, ";
			}
			
			for (int i = 0; i < fields.length; i++)
			{
				String s = fields[i];
				
				if (s != null)
				{
					s = s.trim();
				}
				
				if (i == 0)
				{
					sql += "'" + s + "'" +" ";
				}
				else
				{
					sql += ", '" + s + "'";
				}
			}
			sql += " );\n\r";
			
			bw.write(sql);
			
		}
		
		bw.flush();
		br.close();
		bw.close();
		
	}

	public static void exportData(String sql, String path, String split) throws Exception
	{
		ResultSet rs = conn.createStatement().executeQuery(sql);
		
		BufferedWriter bw = new BufferedWriter(new FileWriter(path));
		
		int cols = rs.getMetaData().getColumnCount();
		String str = null;
		
		while(rs.next())
		{
			str = "";
			
			for(int i = 1; i <= cols; i++)
			{
				if (i == 1)
				{
					str += rs.getObject(i).toString();
				}
				else
				{
					str += split + rs.getObject(i).toString();
				}
			}
			
			bw.write(str);
			bw.write("\n\r");
		}
		
		bw.flush();
		bw.close();
	}
	
}
